package com.wei.servlets;

import com.wei.pojo.Sp;
import com.wei.service.SpService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author 魏小杭
 */
public class SpServlet extends HttpServlet {

    private SpService service;
    @Override
    public void init() throws ServletException {
        service = new SpService();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //1.获取页码 条数
        String pageIndex = req.getParameter("page");
        String countStr = req.getParameter("count");

        //默认页码和条数
        int page = 1;
        int count = 5;

        //判断是否存有效
        try {
            //page 和count 必须得大于0
            if (Integer.valueOf(pageIndex) > 0){ //如果参数有效
                page = Integer.valueOf(pageIndex);//使用参数
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        //单独捕获异常，如果放到一块的话 第一个转换失败 第二个就不会执行了
        try {
            if (Integer.valueOf(countStr) > 0){//如果参数有效
                count = Integer.valueOf(countStr);//使用参数
            }

        }catch (Exception e){
            e.printStackTrace();
        }


        List<Sp> spList = service.selectSpByPage(page,count);

        //总页数
        int sumPage = service.selectSumPage(count);
        //将splist 和 总页数 当前页面 带给jsp
        req.setAttribute("spList",spList);
        req.setAttribute("sumPage",sumPage );
        req.setAttribute("page",page );

        //跳转页面 此时携带参数 必须使用请求转发
        req.getRequestDispatcher("index.jsp").forward(req,resp);





    }
}
